package cn.dxh.stagefinal.controller;

import cn.dxh.stagefinal.bean.CommBrand;
import cn.dxh.stagefinal.bean.CommType;
import cn.dxh.stagefinal.bean.Commodity;
import cn.dxh.stagefinal.bean.SalesChannel;
import cn.dxh.stagefinal.service.CommodityService;
import cn.dxh.stagefinal.utils.BaseWriteInfo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 2019/12/9 21:46
 *
 * @author Wenhao Lee
 * 心向远方，不负厚望。
 */
@Controller
public class CommodityController {

    @Autowired
    private CommodityService commodityService;

    @RequestMapping("/comm/findComm.do")
    public String findComm(@RequestParam(defaultValue = "1") Integer pageIndex,
                           String commName, Integer commBrand, Integer commType, Integer state,
                           ModelMap modelMap) {
        if (pageIndex == 0) {
            pageIndex = 1;
        }
        PageInfo<Commodity> info = commodityService.findCommodity(pageIndex, commName, commBrand, commType, state);
        List<CommType> types = commodityService.findAllType();
        List<CommBrand> brands = commodityService.findAllBrand();
        info.getList().forEach(commodity -> System.out.println(commodity.getState()));
        modelMap.addAttribute("currentPage", info)
                .addAttribute("commName", commName)
                .addAttribute("commBrand", commBrand)
                .addAttribute("commType", commType)
                .addAttribute("state", state)
                .addAttribute("types", types)
                .addAttribute("brands", brands);
        return "/commodity/comm_list";
    }

    @RequestMapping("/comm/findCommById.do")
    public String findCommById(Integer id, ModelMap modelMap) {
        Commodity commodity = commodityService.findCommById(id);
        List<SalesChannel> channels = commodityService.findAllChannel();
        modelMap.addAttribute("channels", channels);
        modelMap.addAttribute("result", commodity);
        commodity.getChannelList().forEach(channel -> System.out.println(channel.getId()));
        return "/commodity/comm_edit";
    }

    @RequestMapping("/comm/updateComm.do")
    public void updateComm(Commodity commodity,
                           @RequestParam("channelIds") List<Integer> channelIds,
                           HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int len = commodityService.updateComm(commodity, channelIds);
        if (len > 0) {
            out.println(String.format(BaseWriteInfo.ALERT_AND_REDIRECT, "更新成功", "/comm/findComm.do"));
        } else {
            out.println(String.format(BaseWriteInfo.ALERT_AND_BACK, "更新失败"));
        }
    }

    @RequestMapping("/comm/addChannel.do")
    public void addChannel(SalesChannel channel, HttpServletResponse response, String successPage) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int len = commodityService.addChannel(channel);
        if (len > 0) {
            out.println(String.format(BaseWriteInfo.ALERT_AND_REDIRECT, "添加成功", successPage));
        } else {
            out.println(String.format(BaseWriteInfo.ALERT_AND_BACK, "添加失败"));
        }
    }

    @RequestMapping("/comm/addComm.do")
    public void addComm(Commodity commodity, @RequestParam("channelIds") List<Integer> channelIds, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int len = commodityService.addComm(commodity, channelIds);
        if (len > 0) {
            out.println(String.format(BaseWriteInfo.ALERT_AND_REDIRECT, "添加成功", "/comm/findComm.do"));
        } else {
            out.println(String.format(BaseWriteInfo.ALERT_AND_BACK, "添加失败"));
        }
    }

    @RequestMapping("/comm/view.do")
    public String view(Integer id, ModelMap modelMap) {
        Commodity commodity = commodityService.findCommById(id);
        modelMap.addAttribute("result", commodity);
        return "/commodity/comm_view";
    }

    @RequestMapping("/comm/exportToExcel.do")
    public ResponseEntity<byte[]> exportToExcel(@RequestParam("ids") List<Integer> ids) throws IOException {
        String path = commodityService.exportToExcel(ids);
        File file = new File(path);
        FileInputStream fis = new FileInputStream(file);
        byte[] b = new byte[fis.available()];
        fis.read(b);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=" + file.getName());
        HttpStatus status = HttpStatus.OK;
        return new ResponseEntity<>(b, headers, status);
    }

    @RequestMapping("/comm/findSalesChannel.do")
    public String findSalesChannel(@RequestParam(defaultValue = "1") Integer pageIndex, String channelName, ModelMap modelMap) {
        PageInfo<SalesChannel> pageInfo = commodityService.findSalesChannel(pageIndex, channelName);
        modelMap.addAttribute("currentPage", pageInfo).addAttribute("channelName", channelName);
        return "/commodity/sales_channel_list";
    }

    @RequestMapping("/comm/goToAddChannel")
    public String goToAddChannel(@RequestParam(required = false) String successPage, ModelMap modelMap) {
        modelMap.addAttribute("sPage", successPage);
        return "/commodity/addChannel";
    }

    @RequestMapping("/comm/goToAddComm")
    public String goToAddComm(ModelMap modelMap) {
        modelMap.addAttribute("channels", commodityService.findAllChannel());
        return "/commodity/comm_add";
    }

    @RequestMapping("/comm/goToPromotion")
    public void goToPromotion(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println(String.format(BaseWriteInfo.REDIRECT, "/comm/findComm.do?state=2"));
    }


}
